package Chuong08;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class ICQClient  {
	public static void main(String args[]) {

		JFrame frame = new ChatFrame();

		frame.setSize(630, 200);
		frame.setTitle("Chat Room");
		frame.show();
	}
}

class ChatFrame extends JFrame {
	private String serverAdd;
	private int portNum;
	private Socket server;
	private PrintWriter out;
	private JTextField outMessage;
	private JTextArea inMessages;

	public ChatFrame() {
		// get server and port info
		String hostnameInput = JOptionPane.showInputDialog(this, "Enter host name",
								"Server Address", JOptionPane.QUESTION_MESSAGE);

		String portnumInput = JOptionPane.showInputDialog(this, "Enter port number",
			"Server Port", JOptionPane.QUESTION_MESSAGE);

       // exception handling
		try {
			InetAddress.getAllByName(hostnameInput);
		} catch (UnknownHostException uhe) {
			JOptionPane.showMessageDialog(this, "The server internet address is not resolvable",
				"Invalid Server Address", JOptionPane.ERROR_MESSAGE);

		}


	    serverAdd = hostnameInput;
		portNum = Integer.parseInt(portnumInput);


		// set up GUI
		inMessages = new JTextArea();
		JScrollPane inPane = new JScrollPane(inMessages);

		JLabel sendLabel = new JLabel("Message:");
		outMessage = new JTextField(30);
		JButton sendButton = new JButton("Send");
		JButton clearButton = new JButton("Clear");
		JButton quitButton = new JButton("Quit");

		Container contentPane = getContentPane();
		contentPane.add( inPane, "Center" );

		JPanel panel = new JPanel();
		panel.add( sendLabel );
		panel.add( outMessage );
		panel.add( sendButton );
		panel.add( clearButton );
		panel.add( quitButton );

		contentPane.add(panel, "South");

       // when "Send" button clicked, send out message in
       // outMessage text field
		sendButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				out.println(outMessage.getText());
				out.flush();

				// echo out-bound message
				inMessages.append(outMessage.getText() +"\n");
			}
		});

        // when "Clear" button is clicked, clear outMessage field
		clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				outMessage.setText("");
			}
		});

       // when "Quit" button is clicked, inform server of quitting
       // and then quit
		quitButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				out.println("quit");
				out.flush();

				System.exit(1);
			}
		});
			try {
					// make connection
					server = new Socket(serverAdd, portNum);

		           // stream for sending info to server
					out = new PrintWriter (server.getOutputStream());

					// new thread to handle incoming messages
					// otherwise cannot interact with gui anymore
					new MessageReceiver( server, inMessages ).start();
				} catch (UnknownHostException e) {
					inMessages.append(" Error " +e);
				} catch (IOException e ) {
					inMessages.append(" Error " + e);
		}
	}

}

class MessageReceiver extends Thread {
	private Socket server;
	private JTextArea inMessages;

	public MessageReceiver(Socket s, JTextArea in) {
		server = s;
		inMessages = in;
	}

	public void run() {
		try {
			// create stream for reading from server
			BufferedReader in = new BufferedReader(
				  new InputStreamReader(server.getInputStream()));

		    // get info from server and display it to the inMessages text field
			while (true) {
				String line = in.readLine();
				inMessages.append(line);
				inMessages.append("\n");

             // how to stop this thread?
			}
		} catch (IOException e) {
			System.out.println("Error" + e);
		}
	}
}